package com.game.server.system;

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.log4j.Log4j;

import com.game.majiang.config.LogManager;
import com.game.server.message.IRespose;


public abstract class AbstractServer extends AbstractBase {
  // [start] ����ģ��
  private HashMap<Integer, AbstractRoom> rooms;

  public AbstractServer(int id) {
    super(id);
    rooms = new HashMap<Integer, AbstractRoom>();
  }

  /**
   * ���ӷ���
   *
   * @param client
   */
  public void addRoom(AbstractRoom room) {
    synchronized (rooms) {
      if (!rooms.containsKey(room.id)) rooms.put(room.id, room);
    }
  }

  /**
   * ���ٷ���
   *
   * @param client
   */
  public void removeRoom(AbstractRoom room) {
    synchronized (rooms) {
      if (rooms.remove(room.id) != null) {
        LogManager.getInstance().Log("ID:" + room.id + "�ر�");
      }
    }
  }

  /**
   * ��÷����б�
   *
   * @return
   */
  @SuppressWarnings("unchecked")
  public Collection<AbstractRoom> getRooms() {
    synchronized (rooms) {
      return ((Map<Short, AbstractRoom>) rooms.clone()).values();
    }
  }

  /**
   * ��õ�������
   *
   * @param roomId
   * @return
   */
  public AbstractRoom getRoom(int roomId) {

    for (AbstractRoom room : getRooms()) {
      if (roomId == room.id) {
        LogManager.getInstance().Log("循环查找到roomid：" + room.id);
        return room;
      }
    }
    return null;
  }

  /*
   * ��÷�������
   */
  public int GetRoomSize() {
    return rooms.size();
  }
  // [end]

  /**
   * 广播
   */
  public void Broadcast(IRespose rsp) {
    LogManager.getInstance().Log("全服广播消息:" + rsp.GetMsgCode());
    ByteBuffer bb = rsp.Serialize();
    for (AbstractClient c : this.getClients()) {
      if (c.getSession() != null) {
        c.getSession().send(bb);
      }
    }
  }


}
